import React, {useState} from "react";
import {Button, Form, Input, Modal, Select} from "antd";
import {addArticleUrl, editArticleUrl, getArticleInfoByIdUrl} from "@/api/blog/article.ts";
import useGetDict from "@/hooks/useGetDict.ts";
import {selectOptions} from "@/components/DictTag";
import {splitString} from "@/utils/common.ts";
import UploadPicture from "@/components/Upload/UploadPicture";
import {globalMessageApi} from "@/components/OpComponent/Message";
import {getUploadUrl, UploadIssueEnum, UploadProjectEnum} from "@/utils/upload.ts";

interface Values {
    artId?: string;
    artTitle: string;
    artCategoryId: string;
    artTag: string;
    sort?: string;
}


export default React.forwardRef((props: any, ref: any) => {

    const {
        getList
    } = props
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isModalEdit, setIsModalEdit] = useState(false)

    const dictData = useGetDict("art_category", "art_tag", "status")
    const [statue, setStatue] = useState(0)

    const [form] = Form.useForm()
    const [formValues, setFormValues] = useState<Values>();
    const [fileList, setFileList] = useState<any[]>([])
    const [uploadUrl, setUploadUrl] = useState("")
    const handleOk = () => {
        form.validateFields().then((values) => {
            if (isModalEdit) {
                editArticleUrl({
                    ...values,
                    artId: formValues?.artId,
                    artTag: values.artTag.join(",")
                }).then((res: any) => {
                    globalMessageApi.success(res.msg)
                    setIsModalOpen(false);
                    getList()
                })
            } else {
                addArticleUrl({
                    ...values,
                    artTag: values.artTag.join(",")
                }).then((res) => {
                    globalMessageApi.success(res.msg)
                    setIsModalOpen(false);
                    getList()
                })

            }
        })
    };


    const handleCancel = () => {
        setIsModalOpen(false);
        // 将表单重置
        form.resetFields();
    }

    const openModal = (data = {artId: null}) => {
        if (data && data.artId) {
            setIsModalEdit(true)
            getArticleInfoByIdUrl({artId: data.artId}).then((res: any) => {
                const coverFiles = res.data.coverFiles || []
                setFileList(coverFiles.map((item: any) => {
                    return {
                        uid: item.id,
                        name: item.fileName,
                        status: 'done',
                        url: item.url
                    }
                }))
                setStatue(res.data.status)
                setFormValues(res.data);
                form.setFieldsValue({
                    ...res.data,
                    artCategoryId: res.data.artCategoryId ? res.data.artCategoryId.toString() : "",
                    artTag: splitString(res.data.artTag),
                })
                setUploadUrl(getUploadUrl(UploadProjectEnum.ARTICLE_PRO_03, UploadIssueEnum.ARTICLE_COVER, res.data.artId))
                setIsModalOpen(true)
            })
        } else {
            setIsModalEdit(false)
            setIsModalOpen(true)
        }
    }

    const handlePublish = () => {
        form.validateFields().then((values) => {
            editArticleUrl({
                ...values,
                artId: formValues?.artId,
                artTag: values.artTag.join(","),
                status: statue == 0 ? 1 : 0
            }).then((res: any) => {
                globalMessageApi.success(res.msg)
                setIsModalOpen(false);
                getList()
            })
        })
    }

    React.useImperativeHandle(ref, () => ({
        openModal: openModal
    }))
    return <Modal title={isModalEdit ? "编辑文章基础信息" : "新增文章基础信息"}
                  open={isModalOpen} onOk={handleOk} onCancel={handleCancel}
                  modalRender={(dom) => (
                      <Form form={form} initialValues={formValues}>
                          {dom}
                      </Form>
                  )}
                  footer={(_, {OkBtn, CancelBtn}) => (
                      <>
                          {isModalEdit &&
                              <Button onClick={handlePublish}>{statue === 0 ? "发布" : "取消发布"}</Button>}
                          <CancelBtn/>
                          <OkBtn/>
                      </>
                  )}
    >
        <Form.Item name={"artTitle"} label="文章标题"
                   rules={[{required: true, message: '文章标题不能为空!'}]}>
            <Input placeholder="请输入文章标题"/>
        </Form.Item>
        <Form.Item name={"artCategoryId"} label="文章分类"
                   rules={[{required: true, message: '请选择文章分类!'}]}
        >
            <Select placeholder={'请选择文章分类'}>
                {selectOptions(dictData.art_category)}
            </Select>
        </Form.Item>
        <Form.Item name={"artTag"} label="文章标签"
                   rules={[{required: true, message: '请选择文章标签!'}]}
        >
            <Select mode="multiple" placeholder={'请选择文章标签'}>
                {selectOptions(dictData.art_tag)}
            </Select>
        </Form.Item>
        <Form.Item name={"sort"} label="文章排序" rules={[{required: true, message: '请输入文章序号!'}]}>
            <Input type="number" placeholder="请输入文章序号"/>
        </Form.Item>
        {isModalEdit && <Form.Item name={"fileId"} label="封面图片">
            <UploadPicture fileList={fileList} url={uploadUrl}/>
        </Form.Item>}
    </Modal>
})
